<template>
  <div style="display: flex; flex-direction: column; height: 100%;">
    <el-tabs class="group-tabs"
             v-model="active"
             :stretch="false"
             tab-position="top"
             @tab-click="tabClick"
             @tab-remove="removeTab">
      <el-tab-pane class="route-tab-pane" :closable="pageList.length > 1" v-for="(page) in pageList"
                   :key="page.path" :name="page.path" :label="page.meta.title"
      style="padding: 0;margin: 0;">
      </el-tab-pane>
    </el-tabs>

    <RouteView style="flex: 1; padding: 16px;"/>

  </div>
</template>

<script setup lang="ts">
import {ref, onMounted, watch} from 'vue';
import router from "@/router";
import {useRoute} from "vue-router";
import {MENU_TYPE} from "@/stores/conf";
import RouteView from "@/components/common/RouteWrap.vue";

const active = ref();
const pageList = ref([]);
const route = useRoute();

const props = withDefaults(defineProps<{
  prefix: string,
}>(), {});

const tabClick = (ctx: any) => {
  const index: number = parseInt(ctx.index);
  router.push({
    path: pageList.value[index].path
  })
}

const removeTab = (targetName: string) => {
  const tabs = pageList.value
  let activeName = active.value;

  if (tabs.length > 1) {
    let removePath: boolean = false;
    if (activeName === targetName) {
      tabs.forEach((tab, index) => {
        if (tab.path === targetName) {
          removePath = true;
          const nextTab = tabs[index + 1] || tabs[index - 1];
          if (nextTab) {
            activeName = nextTab.path
          }
        }
      })

      if (removePath) {
        pageList.value = tabs.filter((tab) => tab.path !== targetName);

        router.push({
          path: activeName
        })
      }
    }
  }
}

const addRoute = (currentRoute: any) => {
  if (currentRoute.meta.type === MENU_TYPE.MENU &&
      currentRoute.path.startsWith(props.prefix)) {
    console.log('--- 标签路由', currentRoute);
    const exist: any = pageList.value.find((item: any) => item.path === currentRoute.path);
    if (!exist) {
      pageList.value.push(currentRoute);
    }
    active.value = currentRoute.path;
  }
}

watch(() => route.path, () => {
  addRoute(router.currentRoute.value);
})

onMounted(() => {
  addRoute(router.currentRoute.value);
})

</script>

<style scoped>
.el-form-item-class .el-form-item__label {
  font-size: 12px;
}

.group-tabs {
  padding: 4px 0 4px 0;
  margin: 0;
  background-color: #fff;
}

.group-tabs >>> .el-tabs__header {
  padding: 0 0 0 16px;
  margin: 0;
}

.group-tabs:deep(.el-tabs__nav-wrap::after) {
  height: 0 !important;
}

.group-tabs:deep(.el-tabs__item.is-active) {
  font-weight: bold;
}

.group-tabs:deep(.el-tabs__active-bar) {
  background-color: transparent !important;
}

</style>
